package com.itheima.controller;


import com.github.pagehelper.PageInfo;
import com.itheima.domain.Grade;
import com.itheima.domain.Student;
import com.itheima.service.GradeService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private GradeService gradeService;

    @RequestMapping("/findAll")
    public String findAll(HttpServletRequest request, HttpServletResponse response){
        int page = 1;
        int size = 5;
        if(StringUtils.isNotBlank(request.getParameter("page"))){
            page = Integer.parseInt(request.getParameter("page"));
        }
        if(StringUtils.isNotBlank(request.getParameter("size"))){
            size = Integer.parseInt(request.getParameter("size"));
        }
        PageInfo all = studentService.findAll(page, size);
        //将数据保存到指定的位置
        request.setAttribute("page",all);
        return "/WEB-INF/pages/student/student-list.jsp";
    }

    @RequestMapping("/toEdit")
    public String edit(Integer studentno, HttpServletRequest request){
        Student student = studentService.findById(studentno);
        request.setAttribute("student", student);
        List<Grade> gradeList = gradeService.findAll();
        request.setAttribute("gradeList", gradeList);
        return "/WEB-INF/pages/student/student-edit.jsp";
    }


    @RequestMapping(value="/update", method=RequestMethod.POST)
    public String update(@ModelAttribute("student") Student student){
        studentService.update(student);
        return "/student/findAll.action";
    }

    @RequestMapping("/add")
    public String add(HttpServletRequest request){
        List<Grade> gradeList = gradeService.findAll();
        request.setAttribute("gradeList", gradeList);
        return "/WEB-INF/pages/student/student-add.jsp";
    }

    @RequestMapping(value="/save", method=RequestMethod.POST)
    public String save(@ModelAttribute("student") Student student){
        studentService.save(student);
        return "/student/findAll.action";
    }

    @RequestMapping("/deleteById")
    public String deleteById(Integer studentno){
        studentService.delete(studentno);
        return "/student/findAll.action";
    }
}
